package android.slc.appdb.core;

import android.slc.box.db.entity.IDbEntity;
import android.slc.box.db.service.DbEntityMapper;
import android.slc.appdb.sys.service.*;
import android.slc.appdb.sys.service.imp.CsConfigServiceImp;
import android.slc.appdb.sys.service.imp.CsDictDataMapperImp;
import android.slc.appdb.sys.service.imp.CsDictTypeMapperImp;
import android.slc.appdb.sys.service.imp.CsStateMapperImp;
import android.slc.appdb.user.service.UserMapper;
import android.slc.appdb.user.service.imp.UserMapperImp;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author slc
 */
public class DbEntityMaster {
    private final static ConcurrentHashMap<Class<? extends DbEntityMapper<?>>, DbEntityMapper<? extends IDbEntity<? extends Serializable>>> serviceMap = new ConcurrentHashMap<>();

    public static <T extends DbEntityMapper<? extends IDbEntity<? extends Serializable>>> void registerService(Class<T> tClass, T dbEntityMapper) {
        serviceMap.put(tClass, dbEntityMapper);
    }

    /**
     * 获取服务
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T extends DbEntityMapper<? extends IDbEntity<? extends Serializable>>> T getService(Class<T> tClass) {
        T service = (T) serviceMap.get(tClass);
        if (service == null) {
            synchronized (DbEntityMaster.class) {
                service = (T) serviceMap.get(tClass);
                if (service == null) {
                    if (tClass.equals(CsDictTypeMapper.class)) {
                        service = (T) new CsDictTypeMapperImp();
                    } else if (tClass.equals(CsDictDataMapper.class)) {
                        service = (T) new CsDictDataMapperImp();
                    } else if (tClass.equals(CsStateMapper.class)) {
                        service = (T) new CsStateMapperImp();
                    } else if (tClass.equals(CsConfigMapper.class)) {
                        service = (T) new CsConfigServiceImp();
                    } else if (tClass.equals(UserMapper.class)) {
                        service = (T) new UserMapperImp();
                    }
                    if (service != null) {
                        serviceMap.put(tClass, service);
                    }
                }
            }
        }
        return service;
    }

    public interface DaoElementListener<T> {
        void onRemove(int dataDiversityVersion, T data);

        void onPut(int dataDiversityVersion, T data);

        void onComplete();
    }
}
